package com.csmht.tododemo.result;


import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import static com.csmht.tododemo.constant.AutoFillConstant.GET_ID;

@Data
public class PageResult<T> {

    private int code;
    private Data<T> data;
    private String message;


    @Setter
    @Getter
    public static class Data<T> {
        private Long start;
        private List<T> list;

        Data(List<T> list) {
            T last = list.getLast();

            try {
                Method method = last.getClass().getMethod(GET_ID);
                this.start = (Long) method.invoke(last);
                this.list = list;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

        Data(Long start, List<T> list) {
            this.start = start;
            this.list = list;
        }

    }

    public static <T> PageResult<T> success(List<T> list) {
        PageResult<T> tPageResult = new PageResult<>();
        tPageResult.setCode(1);
        if(list != null && !list.isEmpty()) {
            Data<T> data = new Data<>(list);
            tPageResult.setData(data);
        }


        return tPageResult;
    }

    public static <T> PageResult<T> success() {
        return success(null);
    }

    public static <T> PageResult<T> err(String message) {
        PageResult<T> pageResult = new PageResult<>();
        pageResult.setCode(0);
        pageResult.setMessage(message);
        return pageResult;
    }
}
